package mid

import (
	"fmt"
	"net/http"

	"gitee.com/firewing_group/test/someclient"

	"gitee.com/firewing_group/configenv"
	"gitee.com/firewing_group/model/comm"
	"gitee.com/firewing_group/model/ctxdata"
	"gitee.com/firewing_group/model/model/stsession"
	"gitee.com/firewing_group/model/model/stuser"
	"gitee.com/firewing_group/test/utils"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

func AuthMid(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		cc := c.Get("cc").(*ctxdata.Cusctx)

		_animalcc := ctxdata.New(cc.C, someclient.GetAnimalDB(), cc.B)
		ck, err := c.Cookie(configenv.GetEnvOrConfig("ckname"))
		if err != nil {
			cc.Errf("not_login_nockname")
			errstr := "not login nockname"
			return c.JSON(http.StatusBadRequest, comm.Bad(errstr, comm.STATUS_NEED_LOGIN))
		}
		if !stsession.Exist(_animalcc, ck.Value) {
			errstr := fmt.Sprintf("snf_%v", ck.Value)
			cc.Errf(errstr)
			return c.JSON(http.StatusBadRequest, comm.Bad(errstr, comm.STATUS_NEED_LOGIN))
		}
		uid := bson.ObjectIdHex(utils.GetUIDFrSession(ck.Value))
		user := stuser.FindByID(_animalcc, uid)
		if user == nil {
			errstr := fmt.Sprintf("unf_%v", uid)
			cc.Errf(errstr)
			return c.JSON(http.StatusBadRequest, comm.Bad(errstr, comm.STATUS_NEED_LOGIN))
		}
		cc.Logf("auth_ok_%v_uid_is_%v", ck.Value, user.ID)
		ctxdata.SetUser(c, user)
		return next(c)
	}
}
